/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * DateTime: 2018/7/27 21:55
 **/
package com.blogs.service.option.impl;

import com.blogs.common.constant.ErrorConstant;
import com.blogs.common.exception.BusinessException;
import com.blogs.domain.db.Options;
import com.blogs.mapper.OptionMapper;
import com.blogs.service.option.OptionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author hubiao
 */
@Service
public class OptionServiceImpl implements OptionService {

    @Resource
    private OptionMapper optionDao;

    @Override
    @Cacheable(value = "optionsCache", key = "'options_'")
    public List<Options> getOptions() {
        return optionDao.getOptions();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"optionsCache", "optionCache"}, allEntries = true, beforeInvocation = true)
    public void saveOptions(Map<String, String> options) {
        if (null != options && !options.isEmpty()) {
            options.forEach( this::updateOptionByName );
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"optionsCache", "optionCache"}, allEntries = true, beforeInvocation = true)
    public void updateOptionByName(String name, String value) {
        if (StringUtils.isBlank( name )) {
            throw BusinessException.withErrorCode( ErrorConstant.Common.PARAM_IS_EMPTY );
        }
        Options option = new Options();
        option.setName( name );
        option.setValue( value );
        optionDao.updateOptionByName( option );
    }

    @Override
    @Cacheable(value = "optionCache", key = "'optionByname+' + #p0")
    public Options getOptionByName(String name) {
        if (StringUtils.isBlank( name )) {
            throw BusinessException.withErrorCode( ErrorConstant.Common.PARAM_IS_EMPTY );
        }
        return optionDao.getOptionByName( name );
    }
}
